﻿using System;
using System.Collections.Generic;
using System.Text;
using Barbar.UrlGuard.Dal.Persist;
using Barbar.UrlGuard.Dal;

namespace Barbar.UrlGuard.BL.Concrete {
  internal class GraphProvider : IGraphProvider {
    private IHistoryPersistor m_HistoryPersistor;
    private IBrowserProvider m_BrowserProvider;

    public GraphProvider(IHistoryPersistor historyPersistor, IBrowserProvider browserProvider) {
      if (historyPersistor == null)
        throw new ArgumentNullException("historyPersistor");

      if (browserProvider == null) {
        throw new ArgumentNullException("browserProvider");
      }

      m_HistoryPersistor = historyPersistor;
      m_BrowserProvider = browserProvider;
    }
    
    #region IGraphProvider Members

    public void ShowGraph(Guid monitoringEntryID) {
      List<MonitoringCheck> checks = new List<MonitoringCheck>(m_HistoryPersistor.GetAllChecks(monitoringEntryID));
      if (checks.Count < 2)
        return;

      StringBuilder urlBuilder = new StringBuilder("http://chart.apis.google.com/chart?chs=1000x300&cht=lc&chd=t:");
      bool isFirst = true;
      int maxValue = 0;
      foreach (MonitoringCheck check in checks) {
        if (!isFirst) {
          urlBuilder.Append(",");
        }
        int requestLength = (int)check.RequestLength;
        if (requestLength > maxValue) {
          maxValue = requestLength;
        }
        urlBuilder.Append(requestLength);
        isFirst = false;
      }
      urlBuilder.Append("&chds=0,");
      urlBuilder.Append(maxValue);

      m_BrowserProvider.OpenUrl(urlBuilder.ToString());
    }

    #endregion
  }
}
